package com.UKIT.airtickets.Service
import android.os.AsyncTask
import com.google.gson.Gson
import java.net.URL

data class Tikets(
    val searchToken: String,
    val startCity: String,
    val startCityCode: String,
    val endCity: String,
    val endCityCode: String,
    val startDate: String,
    val endDate: String,
    val price: Int
)

data class JsonData(
    val record: List<Tikets>,
    val metadata: Metadata
)

data class Metadata(
    val id: String,
    val private: Boolean,
    val createdAt: String
)

class FetchJsonData(private val listener: OnDataFetchedListener) {
    private val gson = Gson()
    private val jsonUrl = "https://api.jsonbin.io/v3/b/64942cf6b89b1e2299b3394e"

    fun fetchTikets() {
        val task = FetchDataTask(listener)
        task.execute(jsonUrl)
    }

    private inner class FetchDataTask(private val listener: OnDataFetchedListener) :
        AsyncTask<String, Void, JsonData?>() {
        override fun doInBackground(vararg urls: String): JsonData? {
            val jsonString = try {
                URL(urls[0]).readText()
            } catch (e: Exception) {
                null
            }
            return jsonString?.let { gson.fromJson(it, JsonData::class.java) }
        }

        override fun onPostExecute(result: JsonData?) {
            listener.onDataFetched(result)
        }
    }

    interface OnDataFetchedListener {
        fun onDataFetched(data: JsonData?)
    }
}